package com.shitou.springai1.user.service;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hankcs.hanlp.HanLP;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ChineseSegmentService {

    // 存储词典中的地名(ns)
    private final Set<String> locationWords = new HashSet<>();

    public ChineseSegmentService() {
        loadDictionary();
    }

    /**
     * 加载HanLP.txt词典中的地名
     */
    private void loadDictionary() {
        try {
            ClassPathResource resource = new ClassPathResource("dictionary/HanLP.txt");
            InputStream inputStream = resource.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // 跳过注释行
                if (line.startsWith("#")) {
                    continue;
                }

                // 分割行内容
                String[] parts = line.split("\\s+");
                if (parts.length >= 2 && "ns".equals(parts[1])) {
                    locationWords.add(parts[0]);
                }
            }

            log.info("成功加载{}个地名词汇", locationWords.size());
        } catch (IOException e) {
            log.error("加载HanLP词典失败", e);
        }
    }

    /**
     * 对中文文本进行分词
     */
    public List<String> segment(String text) {
        if (StringUtils.isBlank(text)) {
            return new ArrayList<>();
        }

        try {
            // 使用HanLP进行分词
            List<String> terms = HanLP.segment(text).stream()
                    .map(term -> {
                        String word = term.word.trim();
                        // 检查是否是地名
                        if (locationWords.contains(word)) {
                            log.info("发现地名: {}", word);
                        }
                        return word;
                    })
                    .filter(term -> term.length() > 0)
                    .collect(Collectors.toList());

            log.debug("分词结果: {} -> {}", text, terms);
            return terms;
        } catch (Exception e) {
            log.error("分词处理失败: {}", text, e);
            // 失败时返回原始文本作为单个词
            return Collections.singletonList(text.trim());
        }
    }

    /**
     * 提取关键词（去除停用词）
     */
    public List<String> extractKeywords(String text) {
        List<String> segments = segment(text);

        // 定义停用词
        Set<String> stopWords = Set.of(
                "我", "你", "他", "她", "它", "我们", "你们", "他们",
                "是", "的", "了", "在", "有", "和", "跟", "与", "或",
                "但", "却", "如果", "因为", "所以", "然后", "之后",
                "啊", "呀", "呢", "吗", "吧", "哦", "嗯",
                "想", "要", "需要", "可以", "能够", "应该",
                "这个", "那个", "这些", "那些", "一种", "一个"
        );

        return segments.stream()
                .filter(term -> term.length() > 1 || isImportantSingleChar(term))
                .filter(term -> !stopWords.contains(term))
                .collect(Collectors.toList());
    }

    private boolean isImportantSingleChar(String term) {
        // 重要的单字词
        Set<String> importantChars = Set.of("楼", "室", "房", "处", "部", "院", "系");
        return importantChars.contains(term);
    }
}
